<template>
  <div ref="aaa" @click="aaa">
    <el-row>
      <el-col :span="4">
        <el-input
          class="u-select-input"
          placeholder="搜索角色"
          v-model="selectVal"
          clearable
        ></el-input>
        <div class="role-manage">
          <el-table
            :data="selectArr"
            :show-header="false"
            ref="multipleTable"
            border
            id="sort"
            highlight-current-row
          >
            <el-table-column label="名称">
              <template slot-scope="scope">
                <div class="role">
                  <div class="role-name">
                    <el-input
                      v-model="inputValue"
                      v-if="scope.row.isEdit"
                      size="small"
                      @blur="inputConfirm(scope.row)"
                      @click.stop.native
                    ></el-input>
                    <span v-if="!scope.row.isEdit">{{ scope.row.label }}</span>
                  </div>
                  <div>
                    <el-popover
                      placement="right"
                      title="选择配置选项"
                      width="500"
                      trigger="click"
                    >
                      <div class="u-popover">
                        <!-- <el-input v-model=""></el-input> -->

                        <el-form ref="form" label-width="80px">
                          <el-form-item label="配置选项">
                            <el-select
                              v-model="node_type_id"
                              placeholder="请选择"
                            >
                              <el-option
                                v-for="item in typeArr"
                                :key="item.value"
                                :label="item.display_value"
                                :value="item.t_id"
                              ></el-option>
                            </el-select>
                          </el-form-item>
                        </el-form>

                        <el-button
                          class="u-config"
                          type="primary"
                          @click="getConfig()"
                          >开始配置</el-button
                        >
                      </div>
                      <a
                        @click="getUserId(scope.row)"
                        slot="reference"
                        class="u-hover-btn"
                        >配置</a
                      >
                    </el-popover>
                  </div>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
      <!-- 路由权限树 -->
      <el-col :span="7" v-if="typeName == 'permission_resource_router_type'">
        <div>
          <p class="u-info-text">请选择对应节点</p>
          <!-- <el-input class="select_input" placeholder="输入关键字进行过滤" v-model="filterText"></el-input> -->
          <el-tree
            :data="routeTreeData"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
          >
            <div
              class="custom-tree-node"
              @click="routerConfig(data)"
              slot-scope="{ node, data }"
            >
              <div class="z-inline">{{ node.label }}</div>
              <div class="z-inline">
                <el-popconfirm
                  title="确定要为用户添加该节点全部路由？"
                  @onConfirm="addByNodeID(data)"
                  @confirm="addByNodeID(data)"
                >
                  <a @click.stop slot="reference">全选</a>
                </el-popconfirm>
                <el-popconfirm
                  title="确定要为用户清空该节点路由？"
                  @confirm="addByNodeID(data)"
                  @onConfirm="deleteByNodeID(data)"
                >
                  <a @click.stop slot="reference">清空</a>
                </el-popconfirm>
              </div>
            </div>
          </el-tree>
        </div>
      </el-col>
      <!-- 按钮权限树 -->
      <el-col :span="7" v-if="typeName == 'permission_resource_button_type'">
        <div>
          <p class="u-info-text">请选择对应节点</p>
          <!-- <el-input class="select_input" placeholder="输入关键字进行过滤" v-model="filterText"></el-input> -->
          <el-tree
            :data="btnTreeData"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
          >
            <div
              class="custom-tree-node"
              @click="routerConfig(data)"
              slot-scope="{ node, data }"
            >
              <div class="z-inline">{{ node.label }}</div>
              <div class="z-inline">
                <el-popconfirm
                  title="确定要为用户添加该节点全部按钮？"
                  @onConfirm="addBtnByNodeID(data)"
                >
                  <a @click.stop slot="reference">全选</a>
                </el-popconfirm>
                <el-popconfirm
                  title="确定要为用户清空该节点全部按钮？"
                  @onConfirm="deleteBtnByNodeID(data)"
                >
                  <a @click.stop slot="reference">清空</a>
                </el-popconfirm>
              </div>
            </div>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="1">&nbsp;</el-col>
      <!-- 菜单权限树 -->
      <el-col :span="18" v-if="typeName == 'permission_resource_menu_type'">
        <el-tree
          :data="menuTreeList"
          node-key="id"
          default-expand-all
          show-checkbox
          :expand-on-click-node="false"
          :check-strictly="true"
          ref="tree"
          @check="checkGroupNode"
        ></el-tree>
      </el-col>
      <el-col :span="11" v-if="typeName == 'permission_resource_router_type'">
        <h2 class="u-update-btn">
          <div class="u-h-2-info">{{ h2Title }}</div>
          <el-button @click="updataInTable" type="primary"
            >更新选中项</el-button
          >
        </h2>
        <el-table
          :data="tableList"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="multipleTable"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="router_name" label="序号" width="50px">
            <template slot-scope="scope">{{
              (pageIndex - 1) * 10 + scope.$index + 1
            }}</template>
          </el-table-column>
          <el-table-column prop="router_name" label="路由名"></el-table-column>
          <el-table-column
            prop="principal"
            label="负责人"
            width="100px"
          ></el-table-column>
          <el-table-column prop="url" label="URL"></el-table-column>
          <!-- <el-table-column prop="request" label="请求参数"></el-table-column> -->
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-col>
      <el-col :span="11" v-if="typeName == 'permission_resource_button_type'">
        <h2 class="u-update-btn">
          <div class="u-h-2-info">{{ h2Title }}</div>
          <el-button @click="updataInTable" type="primary"
            >更新选中项</el-button
          >
        </h2>
        <el-table
          :data="tableList"
          stripe
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
          ref="multipleTable"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="router_name" label="序号" width="50px">
            <template slot-scope="scope">{{
              (pageIndex - 1) * 10 + scope.$index + 1
            }}</template>
          </el-table-column>
          <el-table-column
            prop="page_name"
            label="页面资源名称"
          ></el-table-column>
          <el-table-column
            prop="btn_key"
            label="按钮值"
            width="100px"
          ></el-table-column>
          <el-table-column
            prop="handle_class"
            label="资源权限验证类"
          ></el-table-column>
          <el-table-column prop="description" label="描述"></el-table-column>
        </el-table>
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :total="totalPage"
          layout="total, sizes, prev, pager, next, jumper"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import {
  manageTree,
  getTree,
  routerResourceLinkList,
  getManageTree,
  // resourceDefinitionList,
  addOrDeleteRouterResourceLinkByNodeId,
  addBatchRouterResourceLink,
  getNodeTargetList,
  addOrDeleteButtonResourceLinkByNodeId,
  buttonResourceLinkList,
  getBtnTree,
  addBatchButtonResourceLink,
  getMenuResourceLinkList,
  addOrDeleteMenuResourceLink
} from '@/api/api'
export default {
  data () {
    return {
      checkedAllType: true,
      node_type_id: '',
      roleList: [],
      selectArr: [],
      selectVal: '',
      typeArr: [],
      routeTreeData: [],
      filterText: '',
      h2Title: '',
      tableList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      roleId: '',
      nodeId: '',
      multipleSelection: [],
      multipleSelectionCopy: [],
      typeName: '',
      btnTreeData: [],
      menuTreeList: [],
      selectList: []
    }
  },
  activated () {
    this.getConfigList()
  },
  watch: {
    selectVal () {
      this.seclctFn()
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    nodeId () {
      this.pageIndex = 1
    }
  },
  methods: {
    clearTable () {
      this.tableList = []
    },
    async addBtnByNodeID (e) {
      // 添加按钮节点树
      let res = await addOrDeleteButtonResourceLinkByNodeId({
        'vo.role_id': this.roleId,
        'vo.resource_type': this.node_type_id,
        'vo.type': 0,
        'vo.node_ids': [e.node_id]
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      //
      if (e.node_id === this.nodeId) {
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      }
    },
    // 删除按钮
    async deleteBtnByNodeID (e) {
      let res = await addOrDeleteButtonResourceLinkByNodeId({
        'vo.role_id': this.roleId,
        'vo.resource_type': this.node_type_id,
        'vo.type': 1,
        'vo.node_ids': [e.node_id]
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '移除成功',
        type: 'success'
      })
      if (e.node_id === this.nodeId) {
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      }
    },
    async updataInTable () {
      let delectArr = []
      if (this.typeName === 'permission_resource_router_type') {
        this.multipleSelectionCopy.map(item => {
          delectArr.push(item.link_id)
        })
        let updateArr = []
        this.multipleSelection.map(item => {
          updateArr.push({
            role_id: this.roleId,
            resource_type: this.node_type_id,
            resource_id: item.id
          })
        })

        let res = await addBatchRouterResourceLink({
          'nice_role_and_permission_resource.id': delectArr,
          'nice_role_and_permission_resource.array': updateArr
        })
        if (res[0]) {
          return
        }
        this.$message({
          message: '更新选项成功',
          type: 'success'
        })
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      } else if (this.typeName === 'permission_resource_button_type') {
        this.multipleSelectionCopy.map(item => {
          delectArr.push(item.link_id)
        })
        let updateArr = []
        this.multipleSelection.map(item => {
          updateArr.push({
            role_id: this.roleId,
            resource_type: this.node_type_id,
            resource_id: item.id
          })
        })

        let res = await addBatchButtonResourceLink({
          'nice_role_and_permission_resource.id': delectArr,
          'nice_role_and_permission_resource.array': updateArr
        })
        if (res[0]) {
          return
        }
        this.$message({
          message: '更新选项成功',
          type: 'success'
        })
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      }
    },
    async addByNodeID (e) {
      console.log(e)
      let res = await addOrDeleteRouterResourceLinkByNodeId({
        'vo.role_id': this.roleId,
        'vo.resource_type': this.node_type_id,
        'vo.type': 0,
        'vo.node_ids': [e.node_id]
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      if (e.node_id === this.nodeId) {
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      }
    },
    async deleteByNodeID (e) {
      let res = await addOrDeleteRouterResourceLinkByNodeId({
        'vo.role_id': this.roleId,
        'vo.resource_type': this.node_type_id,
        'vo.type': 1,
        'vo.node_ids': [e.node_id]
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '移除成功',
        type: 'success'
      })
      if (e.node_id === this.nodeId) {
        this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
      }
    },
    toggleSelection (rows) {
      if (rows) {
        this.$nextTick(() => {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        })
      } else {
        this.$nextTick(() => {
          this.$refs.multipleTable.clearSelection()
        })
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
      console.log(this.multipleSelection)
    },
    async checkGroupNode (currentObj, treeStatus) {
      // 用于：父子节点严格互不关联时，父节点勾选变化时通知子节点同步变化，实现单向关联。
      let selected = treeStatus.checkedKeys.indexOf(currentObj.id) // -1未选中
      let res = await addOrDeleteMenuResourceLink({
        'vo.role_id': this.roleId,
        'vo.menu_id': currentObj.id,
        'vo.type': selected !== -1 ? 0 : 1,
        'vo.resource_type': this.node_type_id
      })
      if (res[0]) {
        return
      }
      this.$message.success(
        selected !== -1 ? '添加菜单角色权限成功！' : '删除菜单角色权限成功！'
      )
      this.getMenuResourceLinkList()
    },
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.routerConfig({ label: this.h2Title, node_id: this.nodeId })
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    async routerConfig (e) {
      this.h2Title = e.label
      this.nodeId = e.node_id
      this.multipleSelection = []
      if (this.typeName === 'permission_resource_router_type') {
        let res = await routerResourceLinkList({
          'vo.node_id': this.nodeId,
          'vo.role_id': this.roleId,
          'page.currPage': this.pageIndex,
          'page.pageSize': this.pageSize
        })
        if (res[0]) {
          return
        }
        this.tableList = res[1].data.pageList.list
        this.totalPage = res[1].data.pageList.totalCount
        this.tableList.map((item, index) => {
          if (item.link_id) {
            this.tableList[index].checked = true
            this.multipleSelection.push(item)
          } else {
            this.tableList[index].checked = false
          }
          //
        })
        this.multipleSelectionCopy = this.multipleSelection
        this.toggleSelection(this.multipleSelection)
      } else if (this.typeName === 'permission_resource_button_type') {
        let res = await buttonResourceLinkList({
          'vo.node_id': this.nodeId,
          'vo.role_id': this.roleId,
          'page.currPage': this.pageIndex,
          'page.pageSize': this.pageSize
        })
        if (res[0]) {
          return
        }
        this.tableList = res[1].data.pageList.list
        this.totalPage = res[1].data.pageList.totalCount
        this.tableList.map((item, index) => {
          if (item.link_id) {
            this.tableList[index].checked = true
            this.multipleSelection.push(item)
          } else {
            this.tableList[index].checked = false
          }
          //
        })
        this.multipleSelectionCopy = this.multipleSelection
        this.toggleSelection(this.multipleSelection)
      }
    },
    aaa () {},
    getUserId (e) {
      this.roleId = e.value
    },
    async getConfig () {
      this.clearTable()
      if (!this.node_type_id) {
        this.$message({
          message: '请选择配置选项',
          type: 'warning'
        })
        return
      }
      this.$refs.aaa.click()
      let typeName = ''
      this.typeArr.map(item => {
        if (parseInt(item.t_id) === parseInt(this.node_type_id)) {
          typeName = item.real_value
        }
      })
      this.typeName = typeName
      if (typeName === 'permission_resource_router_type') {
        // 打开路由
        let res = await getManageTree({
          id: '1'
        })
        if (res[0]) {
          return
        }
        this.routeTreeData = JSON.parse(
          JSON.stringify([res[1].data])
            .split('child')
            .join('children')
        )
        this.routeTreeData = JSON.parse(
          JSON.stringify(this.routeTreeData)
            .split('node_name')
            .join('label')
        )
      } else if (typeName === 'permission_resource_button_type') {
        // 打开按钮btnTreeData
        let res = await getBtnTree({
          id: 1
        })
        if (res[0]) {
          return
        }
        this.btnTreeData = JSON.parse(
          JSON.stringify([res[1].data])
            .split('child')
            .join('children')
        )
        this.btnTreeData = JSON.parse(
          JSON.stringify(this.btnTreeData)
            .split('node_name')
            .join('label')
        )
      } else {
        // 菜单
        this.getMenuResourceLinkList()
      }
    },
    async getMenuResourceLinkList () {
      this.selectList = []
      let res = await getMenuResourceLinkList({
        'vo.role_id': this.roleId
      })
      if (res[0]) {
        return
      }
      this.menuTreeList = JSON.parse(
        JSON.stringify(res[1].data.list)
          .split('name')
          .join('label')
          .split('menu_id')
          .join('id')
          .split('child')
          .join('children')
      )
      this.setName(this.menuTreeList)
      this.$nextTick(() => {
        this.$refs.tree.setCheckedKeys(this.selectList)
      })
    },
    setName (datas) {
      // 遍历树  获取已有权限数组
      for (var i in datas) {
        if (datas[i].link_id) {
          this.selectList.push(datas[i].id)
        }
        if (datas[i].children) {
          this.setName(datas[i].children)
        }
      }
    },
    // 搜索过滤
    seclctFn () {
      this.selectArr = []
      this.roleList.map(item => {
        if (item.label.indexOf(this.selectVal) !== -1) {
          this.selectArr.push(item)
        }
      })
    },
    // 获取所有角色
    async getRoleList () {
      let res = await manageTree({
        tableName: 'nice_role'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        if (data.data.hasOwnProperty('child')) {
          this.roleList = data.data.child.map(ele => {
            return {
              label: ele.role_name,
              value: ele.id,
              isEdit: false
            }
          })
          // this.getAuthorityList()
          this.seclctFn()
        }
      } else {
        this.$message.error(res[1].msg)
      }
    },
    // 权限资源定义列表
    async getConfigList () {
      let res = await getTree({ id: '574', tableName: 'nice_enum_tree' })
      if (res[0]) {
        return
      }
      this.typeArr = res[1].data.child
      this.getRoleList()
    }
  }
}
</script>
<style lang="scss" scoped>
.role-manage {
  // width: 500px;
  height: 760px;
  overflow: auto;
  .role {
    display: flex;
    justify-content: space-between;
    .role-name {
      flex: 1;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
}
.u-select-input {
  // width: 400px;
  margin-bottom: 10px;
}
.u-hover-btn {
  margin-right: 15px;
}
.u-popover {
  padding: 20px;
}
.u-config {
  margin-top: 30px;
  float: right;
  margin-bottom: 10px;
}
.u-info-text {
  padding-left: 10px;
  color: #1e6df5;
}
.z-inline {
  line-height: 40px;
}
.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.u-update-btn {
  display: flex;
  justify-content: space-between;
}
.u-h-2-info {
  margin-top: 8px;
}
.z-flex {
  display: flex;
}
</style>
